package com.bnz.congig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
//    1. 使用系统自带的表单
//     @Override
//     protected void configure(HttpSecurity http) throws Exception {
//     	http.formLogin()        // 使用系统自带的登录表单
//     		.successForwardUrl("/success") //登录成功后跳转到的页面
//     		.and()
//     		.authorizeRequests()           // 除登录相关的其它请求
//     		.anyRequest()
//     		.authenticated();	           // 都要经过认证才能访问
//     }

//    //定制化登录表单 (认证过程)
//     @Override
//     protected void configure(HttpSecurity http) throws Exception {
//     	http.formLogin()
//     		.loginPage("/login.html")               //指定登录表单页面
//     		.loginProcessingUrl("/login")
//     		.successForwardUrl("/success")
//     		.and()
//     		.authorizeRequests()
//     		.antMatchers("/login.html","/webjars/**")  //放行/webjars/**
//     		.permitAll()                            // 其它需要认证访问
//     		.anyRequest()
//     		.authenticated()
//     		.and()
//     		.csrf()         // 禁用csrf功能
//     		.disable();
//     }
//定制化登录表单 (授权过程)
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()
            .loginPage("/login.html")               //指定登录表单页面
            .loginProcessingUrl("/login")
            .successForwardUrl("/success")
            .and()
            .authorizeRequests()
            .antMatchers("/login.html","/webjars/**")  //放行/webjars/**
            .permitAll()                            // 其它需要认证访问
            .anyRequest()
            .authenticated()
            .and()
            .csrf()         // 禁用csrf功能
            .disable();
}

    // 设置密码加密器
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
    }

    //指定加密方式
    @Bean
    public PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
}
